<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="title" width="800px">
    <MyAlert
      v-if="!canWrite"
      type="warning"
      message="当前为系统资源，只能查看"
    />
    <BasicForm @register="registerForm" />
    <template #footer v-if="canWrite">
      <a-button @click="handleSubmit(false)" type="primary" ghost>仅保存</a-button>
      <a-button @click="handleSubmit(true)" type="primary" >保存并关闭</a-button>
    </template>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from "vue"
  import { BasicModal, useModalInner } from "/@/components/Modal"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { formSchema } from "./data"
  import * as resourceApi from "/@/api/iam/resource"
  import { useMessage } from "/@/hooks/web/useMessage"
  import MyAlert from "/@/components/My/MyAlert.vue";
  const { createMessage } = useMessage()
  const emit = defineEmits(["success", "register"])

  const isUpdate = ref(true)
  const namespaceCode = ref()
  const canWrite = ref(true)
  const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
    schemas: formSchema,
    showActionButtonGroup: false,
    labelWidth: 100,
    baseColProps: { lg: 12, md: 12 },
    wrapperCol: { lg: 24, md: 24 },
  })
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields()
    setModalProps({ confirmLoading: false, loading: true})
    isUpdate.value = !!data?.isUpdate
    namespaceCode.value = data.namespaceCode
    try {
      if (unref(isUpdate)) {
        data.record = await resourceApi.getApiResource({ id: data.record.id })
        setProps({ disabled: !data.record.canWrite })
        canWrite.value =data.record.canWrite
        setModalProps({ showOkBtn: canWrite.value, showCancelBtn: canWrite.value })
        await setFieldsValue({ ...data.record })
      }
    } finally {
      setModalProps({ loading: false })
    }
  })

  const title = computed(() => {
    return (!unref(isUpdate) ? "新增资源" : `编辑资源`)
  })
  async function handleSubmit(isClose) {
    try {
      let values = await validate()
      setModalProps({ confirmLoading: true })
      await resourceApi.saveOrUpdateApiResource({ ...values, namespaceCode: namespaceCode.value }, isUpdate.value)
      isClose && closeModal()
      emit("success")
      createMessage.success(`${title.value}成功`)
    } finally {
      setModalProps({ confirmLoading: false })
    }
  }
</script>
